<?php
namespace jy_newlieshop;
defined('BY_JYA') or exit('error');
/*
	分佣佣金
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$is_open=intval($this->setting['is_open']);
		if(!$is_open){
			return;
		}
		if(!is_array($order['api_data'])){
			$order['api_data']=json_decode($order['api_data'],true);
		}
		$order['goods']=pdo_getall('jy_weishop_order_goods',array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
		$fordersn=$order['api_data']['fordersn'];
		$this->order=$order;
		$member=pdo_get('core_members',array('id'=>$order['mid'],'uniacid'=>$_SESSION['uniacid']),array('fromuser'));
		$myagent=pdo_get('jy_newlieshop_member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$order['mid']));
		if($myagent['is_agent']){
			$this->model('member')->update_agent_level($order['mid'],$order['id']);
		}
		$this->commission_order=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$this->order['mid'],
				'agent_id'=>$member['fromuser'],
				'fordersn'=>$fordersn,
				'ordersn'=>$this->order['ordersn'],
				'price'=>$this->order['price'],
				'plugin_name'=>$this->order['plugin_name']?:'',
				'commission_price'=>$this->order['price'],
				'commission_money'=>0,
				'ispay'=>1,
				'status'=>1,
				'createtime'=>TIMESTAMP,
		);
		$fromuser=$member['fromuser'];
		$agent=pdo_get('jy_newlieshop_member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$fromuser));
		$level=pdo_get('jy_newlieshop_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$agent['level_id']));
		$mylevel=pdo_get('jy_newlieshop_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$myagent['level_id']));
		if($fordersn){
			$order=pdo_get('jy_newlieshop_order',array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$fordersn));
			if($order['id'] && $order['status']==1){
				$fanlevel=$level;
				if($order['mid']!=$member['fromuser']){
					$agent=pdo_get('jy_newlieshop_member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$order['mid']));
					$fanlevel=pdo_get('jy_newlieshop_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$agent['level_id']));
				}
				$lastfennum=$this->order_upfan($order,$fanlevel);
			}
		}
		$this->create_commission($agent,$level,$mylevel,$lastfennum);
		//生成分佣订单
		$indata=$this->commission_order;
		$this->insert('order',$indata);
		$this->order_membergoods($indata);
		return true;
	}
	function create_commission($member,$level=array(),$mylevel=array(),$lastfennum=0){
		if($member && $member['is_agent'] && !$member['stop']){
			//相应会员存在且是分销商且状态正常			
			if(!$member['level_id']){
				//获取默认等级佣金比例
				$level=$this->plugin_setting('default_level');
				$level['level']=0;
				$level['id']=0;
				$level_id=0;
			}else{
				$level_id=$level['id'];
			}
			$red_rate=$level['red_rate'];
			if($member['level_id'] && !$mylevel['level_id']){
				//获取默认等级佣金比例
				$mylevel=$this->plugin_setting('default_level');
			}
			if(!$member['level_id']){
				$mylevel=$level;
			}
			$fan_day=$mylevel['fan_day']?:0;
			$fan_num=$mylevel['fan_num']?:0;
			$red_money=0;
			$isbuynum=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'order_price'=>$order_price,
			);
			//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
			//非按笔计算
			$this->needorder=false;
			foreach($this->order['goods'] as $goods){
					if(!$goods['id']){
						$this->needorder=true;
						continue;	
					}
					$goodstotal=$goods['total'];
					$goodsid=$goods['goodsid'];
					$total_price=$goods['total_price']?$goods['total_price']:pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goods['id'],'uniacid'=>$_SESSION['uniacid']),'total_price');
					$goods_commission=$this->get('goods',array('goods_id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']));
					if(!$goods_commission['id']){
						$this->needorder=true;
						continue;
					}
					$order_price=$order_price-$total_price;
					if($goods_commission['ignore']){
						continue;
					}
					$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
					foreach($goods_commission['commissions'] as $gc){
						if($gc['level_id']!=$level_id){
							continue;
						}else{
							$goods_red_rate=$gc['red_rate'];
							break;
						}
					}
					if(substr($goods_red_rate,-1)=='%'){
						$goods_red_money=($total_price*substr($goods_red_rate,0,-1))/100;
						$red_money+=$goods_red_money;
					}else{
						$goods_red_money=$goods_red_rate*$goods['total'];
						$red_money+=$goods_red_money;
					}
					$remark['goods_commission'][]=array('ordergoodsid'=>$goods['id'],'goods_id'=>$goods['goodsid'],'total_price'=>$total_price,'total'=>$goods['total'],'commission_per'=>$goods_red_rate,'commission_money'=>$goods_red_rate);
			}
			$this->commission_order['goodsid']=$goodsid;
			$this->commission_order['goodstotal']=$goodstotal;
			if($this->needorder || count($this->order['goods'])<=0){
				if(substr($red_rate,-1)=='%'){
					$money=intval($order_price*substr($red_rate,0,-1))/100;
				}else{
					$money=$red_rate;
				}
				$red_money+=$money;
			}
			if($red_money>0 && !$lastfennum){
				$this->commission_order['commission_money']+=$red_money;
				$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'mid'=>$member['mid'],
						'ordersn'=>$this->order['ordersn'],
						'money'=>$red_money,
						'type'=>2,
						'remark'=>ijson_encode($remark),
						'createtime'=>TIMESTAMP,
						'status'=>$this->setting['isbuy_jiesuan']?2:0,
				);
				$this->insert('commission',$new_commission);
				if($this->setting['isbuy_jiesuan']){
					model('core/member')->member_credit($member['mid'],'credit2',$red_money,true,'jy_newlieshop','直推奖励');
				}
			}
			if($fan_day){
				$fenendtime=time()+$fan_day*24*3600;
			}else{
				$fenendtime=0;
			}
			$this->commission_order['commission_money']+=$this->order['price'];
			$status=$this->setting['isbuy_jiesuan']?1:0;
			$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'mid'=>$member['mid'],
						'ordersn'=>$this->order['ordersn'],
						'money'=>$this->order['price'],
						'goodsid'=>$goodsid,
						'lastfennum'=>$fan_num,
						'type'=>1,
						'remark'=>ijson_encode($remark),
						'fenendtime'=>$fenendtime,
						'createtime'=>TIMESTAMP,
						'status'=>$status,
			);
			$this->insert('commission',$new_commission);
		}
		return 0;
	}
	public function order_upfan($order=array(),$level=array()){
		if(!$level['id']){
			$level=$this->plugin_setting('default_level');
		}
		$isfan=0;
		$fan_day=$level['fan_day'];
		$fan_num=$level['fan_num'];
		if($fan_num){
			//$isbuynum=pdo_getsum('jy_newlieshop_order',array('fordersn'=>$order['ordersn'],'uniacid'=>$_SESSION['uniacid']),'goodstotal');
		}
		$item=$this->get('commission',array('type'=>1,'ordersn'=>$order['ordersn'],'mid'=>$order['mid'],'status'=>array(0,1),'uniacid'=>$_SESSION['uniacid']));
		if($item['lastfennum']){
				if(!$item['fenendtime'] || $item['fenendtime']>TIMESTAMP){
					$this->update('commission',array('lastfennum -='=>1),array('id'=>$item['id'],'uniacid'=>$_SESSION['uniacid']));
				}else{
					$this->update('commission',array('status'=>3),array('id'=>$item['id'],'uniacid'=>$_SESSION['uniacid']));
					$this->update('order',array('status'=>4),array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
				}
		}elseif($item['status']==1){
				$this->update('commission',array('status'=>2),array('id'=>$item['id'],'uniacid'=>$_SESSION['uniacid']));
				$this->update('order',array('status'=>2),array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
				model('core/member')->member_credit($item['mid'],'credit2',$item['money'],true,'jy_newlieshop','全返');
		}
		if($item['lastfennum'] && (!$item['fenendtime'] || $item['fenendtime']>TIMESTAMP)){
				$isfan=1;	
		}
		return $isfan;
	}
	public function order_membergoods($order=array()){
		$fennum=pdo_count('jy_newlieshop_member',array('agent_id'=>$order['mid'],'uniacid'=>$_SESSION['uniacid']));
		$buynum=pdo_getsum('jy_newlieshop_order',array('mid'=>$order['mid'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']),'goodstotal');
		$fee=pdo_getsum('jy_newlieshop_commission',array('mid'=>$order['mid'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']),'money');
		$update=array(
			'fennum'=>$fennum,
			'buynum'=>$buynum,
			'fee'=>$fee,
		);
		$id=pdo_getcolumn('jy_newlieshop_membergoods',array('mid'=>$order['mid'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']),'id');
		if($id){
			pdo_update('jy_newlieshop_membergoods',$update,array('mid'=>$order['mid'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']));
		}else{
			$update['uniacid']=$_SESSION['uniacid'];	
			$update['mid']=$_SESSION['uid'];
			$update['goodsid']=$order['goodsid'];	
			pdo_insert('jy_newlieshop_membergoods',$update);
		}
		if($order['agent_id']){
			$fennum=pdo_count('jy_newlieshop_member',array('agent_id'=>$order['agent_id'],'uniacid'=>$_SESSION['uniacid']));
			$buynum=pdo_getsum('jy_newlieshop_order',array('mid'=>$order['agent_id'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']),'goodstotal');
			$fee=pdo_getsum('jy_newlieshop_commission',array('mid'=>$order['agent_id'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']),'money');
			$update=array(
				'fennum'=>$fennum,
				'buynum'=>$buynum,
				'fee'=>$fee,
			);
			$id=pdo_getcolumn('jy_newlieshop_membergoods',array('mid'=>$order['agent_id'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']),'id');
			if($id){
				pdo_update('jy_newlieshop_membergoods',$update,array('mid'=>$order['agent_id'],'goodsid'=>$order['goodsid'],'uniacid'=>$_SESSION['uniacid']));
			}else{
				$update['uniacid']=$_SESSION['uniacid'];	
				$update['mid']=$order['agent_id'];
				$update['goodsid']=$order['goodsid'];	
				pdo_insert('jy_newlieshop_membergoods',$update);
			}
		}
		return 0;
	}
	public function order_complete($order){
		$this->update('commission',array('status'=>2,'complete_time'=>TIMESTAMP),array('ordersn'=>$order['ordersn'],'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		$this->update('order',array('status'=>3),array('ordersn'=>$order['ordersn'],'uniacid'=>$_SESSION['uniacid']));
		$fee=$this->get('commission',array('ordersn'=>$order['ordersn'],'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		if($fee['type']==2 && $fee['money']>0){
			model('core/member')->member_credit($fee['mid'],'credit2',$fee['money'],true,'jy_newlieshop','直推奖励');
		}elseif($fee['type']==1 && $fee['money']>0 && !$fee['lastfennum']){
			model('core/member')->member_credit($fee['mid'],'credit2',$fee['money'],true,'jy_newlieshop','全返');
		}
		return 0;
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$money=pdo_getsum('jy_commission_commission',$params,'money');
		if($money<=0){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=$this->count('commission',$params,'id');
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'mobile'=>$post['mobile'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per'] && ($post['pay_type']!='credit' || !$this->setting['balance_credit'])){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		$update=array(
			'status'=>2,
			'balancesn'=>$new_balance['balancesn'],
		);
		$this->update('commission',$update,$params);
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
		return true;
		/*$update=array(
			'status'=>1,
			'balancesn'=>'',
		);
		$balance=$this->get('balance',array('id'=>$balance_id),array('mid','balancesn'));
		if($balance['balancesn']){
			$this->update('commission',$update,array('uniacid'=>$_SESSION['uniacid'],'mid'=>$balance['mid'],'balancesn'=>$balance['balancesn']));
		}*/
		return true;
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			//exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_trade_no'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		if($pay_type){
			$update['pay_type']=$pay_type;
		}
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		线下打款
	*/
	protected function pay_balance_by_downline(){
		return 'pay_trade_no';
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,'jy_commission','分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		if(!$res['payment_no'] && !$res['batch_id']){
			exi('打款到微信零钱失败！','error');
		}
		return $res['payment_no']?:$res['batch_id'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}
}